<template>
  <div>
    <div class="center">
      <!-- 头部 -->
      <div class="table_header flex flex_bet flex-wrap">
        <div class="table_button">
          <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addLogo">添加</el-button>
        </div>
        <div class="table_searchs flex">
          <div class="table_search flex">
            <el-input placeholder="搜索" v-model="searchInput" class="input-with-select" size="small">
              <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
                <el-option label="归属" value="1"></el-option>

              </el-select>
              <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
            </el-input>
          </div>
          <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
        </div>
      </div>
      <!-- table -->
      <el-table stripe style="width: 100%" :data="browserTable" :key="key" border fit highlight-current-row ref="tableDataRef">
        <el-table-column v-if="colData[0].istrue" min-width="50" align="center" prop="id" label="ID"></el-table-column>
        <el-table-column v-if="colData[1].istrue" min-width="120" align="center" prop="admin_name" label="归属"></el-table-column>
        <el-table-column v-if="colData[2].istrue"  min-width="100" align="center" prop="batch" label="分发批次">
          <template slot-scope="scope">
            <p v-for="(item,index) in scope.row.batch" :key="item.id" style="margin: 0;padding: 0">{{item.batch}}</p>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[3].istrue"  min-width="80" align="center" prop="childAdmin" label="分发子账号">
          <template slot-scope="scope">
            <p v-for="(item,index) in scope.row.childAdmin" :key="item.id"  style="margin: 0;padding: 0">{{item.username}}</p>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[4].istrue" min-width="120" align="center" prop="nameCode" label="型号"></el-table-column>
        <el-table-column v-if="colData[5].istrue" min-width="100" align="center" prop="file_url" label="文件地址">
          <template slot-scope="scope">
            <div class="flex flex_cen">
              <i class="iconfont iconzip1 download" style="border:none;background-color:inherit;color:#409EFF">
                <a target="_blank" :href="scope.row.file_url"></a>
              </i>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="colData[6].istrue" min-width="80" align="center" prop="file_size" label="文件大小">
          <template slot-scope="scope">
            {{scope.row.file_size | zhDate}}
          </template>
        </el-table-column>
        <el-table-column v-if="colData[7].istrue"  min-width="130" align="center" prop="remark" label="备注"></el-table-column>
        <el-table-column v-if="colData[8].istrue" min-width="70" align="center" prop="admin_name" label="创建人"></el-table-column>
        <el-table-column v-if="colData[9].istrue" min-width="140" align="center" prop="create_time" label="创建时间">
          <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
        </el-table-column>
        <el-table-column min-width="150" align="center" prop="log" label="操作">
          <template slot-scope="scope">
            <el-row>
              <el-button size="mini" type="primary" @click="getqueryIdLogoImg(scope.row.id)">编辑</el-button>
              <el-button size="mini" @click="getdeleteLogoImg(scope.row.id)">删除</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="paging">
        <el-pagination background :current-page.sync="listQuery.startSize" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
        </el-pagination>
      </div>
      <!-- 删除弹窗 -->
      <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
    </div>
    <el-dialog title="设备开机动画远程DIY定制" :visible.sync="logShow" width="40%" :close-on-click-modal="false" :close-on-press-escape="false" @close="redactFormclose">
      <el-form :model="addForm" ref="ruleForm" :rules="rules">
        <el-form-item label="产品型号:" label-width="100px"  prop="name_code">
          <el-select v-model="addForm.sn_three_four" placeholder="请选择" filterable>
            <el-option
              v-for="item in nameCodeOptions"
              :key="item.name_code"
              :label="item.name"
              :value="item.name_code"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分发方式:" label-width="100px" prop="send_type">
          <el-radio-group v-model="addForm.send_type" @input="resetBatchAndChild">
            <el-radio :label="1">批次</el-radio>
            <el-radio :label="2">子账号</el-radio>
            <el-radio :label="3">批次和子账号</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="批次:" v-show="addForm.send_type==1 || addForm.send_type==3" label-width="100px">
          <el-select v-model="addForm.batch"  multiple filterable placeholder="请选择批次">
            <el-option
              v-for="item in batchArr"
              :key="item.id"
              :label="item.batch"
              :value="item.id.toString()">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子账号:" v-show="addForm.send_type==2 || addForm.send_type==3" label-width="100px">
          <el-select v-model="addForm.child_admin"  multiple placeholder="请选择子账号">
            <el-option
              v-for="item in childrenOption"
              :key="item.id"
              :label="item.username"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" label-width="100px">
          <div class="flex felx_align">
            <el-upload class="upload-demo" action="#" id="file" accept=".zip" :data="pdfData" :auto-upload="false" :show-file-list="true" :on-change="logoUpload"  :limit="1"  :on-progress="beforeAvatarUpload" :before-upload="beforeZip">
              <el-button class="logoBtn" type="primary" round style="padding: 12px 67.4px ">{{addForm.file_url ? `已上传` : '选择ZIP包'}} ({{ addForm.file_size | zhDate }})</el-button>
            </el-upload>
          </div>
          <el-progress v-if="videoUploadPercent" :percentage="videoUploadPercent" style="margin-top:10px"></el-progress>
          <el-link :href="operationDoc" type="primary" target="_blank">开机动画ZIP包制作操作指南 下载</el-link>
        </el-form-item>
        <el-form-item label="备注:" label-width="100px" prop="remark">
          <el-input v-model="addForm.remark" :rows="2" maxlength="150" show-word-limit autocomplete="off" placeholder="请输入备注,150字以内" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="logShow  = false" size="mini" round>取 消</el-button>
        <el-button v-if="compileBtn" type="primary" size="mini" round @click="getaddLogoImg('ruleForm')">部署到设备</el-button>
        <el-button v-else type="primary" size="mini" round @click="geteditLogoImg('ruleForm')">修改部署</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryLogoImg, addLogoImg, deleteLogoImg, queryIdLogoImg, editLogoImg } from "@/api/customMade.js";
import { getBatchTwo } from "@/api/equipment.js";
import deleteDialog from "@/components/deleteDialog";
import {getNameCode} from "@/api/appUpdate";
import {getChildAdmin} from "@/api/launcherMade";
import {ossFile} from "@/utils/ossUpload";
import BMF from "browser-md5-file";
export default {
  components: { dynamicTable, deleteDialog },
  data() {
    return {
      checkboxVal: ['ID', '归属', '分发批次', '分发子账号', '型号', '文件地址', '文件大小', '备注', '创建人', '创建时间'],
      key: 1,
      colData: [], //动态控制table
      total: 0,
      searchInput: "",
      select: "1", //搜索条件
      //归属table
      browserTable: [],
      logoImage: '/static/img/defaultLog.394693ff.png',
      imgUrl: '',
      logShow: false,
      listQuery: { userId: localStorage.getItem("ID"), startSize: 1, pageSize: 10, username: undefined },
      batchData: [],
      pdfData: { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip") },
      addForm: { file_url: '', file_size: '', file_md5: '', batch: [], remark: '', sn_three_four: '', child_admin: [], send_type: 1 },
      rules: {
        remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
        batch: [{ required: true, message: "请选择批次", trigger: "blur" }],
      },
      videoUploadPercent: 0,
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
      compileBtn: false,
      logoId: 0,
      dialogFormVisible: false,
      uploadLink: process.env.VUE_APP_BASE_API,
      nameCodeOptions: [],
      childrenOption: [],  //子账号可选框
      batchArr: [],
      operationDoc: 'https://jiaoguanyi008.oss-cn-shenzhen.aliyuncs.com/pdf/%E5%BC%80%E6%9C%BA%E5%8A%A8%E7%94%BB%E5%88%B6%E4%BD%9C%E6%8C%87%E5%8D%97V3.1.rar',
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getqueryLogoImg()
    this.getBatchTwos()
    this.getNameCode();
    this.getBatchTwo()
    this.getChildAdmin()
  },
  methods: {
    //删除
    getdeleteLogoImg(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), last_ip: sessionStorage.getItem("Ip"), id: this.deleteDialogs.deleteId }
      deleteLogoImg(params).then(res => {
        this.$message.success(res.msg)
        this.getqueryLogoImg()
      })
    },
    resetBatchAndChild(e) {
      switch (e) {
        case 1:
          this.addForm.child_admin = [];
          break;
        case 2:
          this.addForm.batch = [];
          break
      }
    },
    //获取型号名称
    getNameCode() {
      getNameCode({userId: localStorage.getItem("id")}).then(res => {
        this.nameCodeOptions = res.data.nameCode
        this.fifthOptions = res.data.fifth
      }).catch(err => {
        this.nameCodeOptions = []
        this.fifthOptions = []
      })
    },
    getBatchTwo() {
      getBatchTwo({ userId: localStorage.getItem("ID") }).then(res => {
        this.batchArr = res.data
      }).catch(err => {
        this.batchArr = []
      })
    },
    getChildAdmin() {
      getChildAdmin({ userId: localStorage.getItem("ID") }).then(res => {
        this.childrenOption = res.data
      }).catch(err => {
        this.childrenOption = []
      })
    },
    redactFormclose() {
      this.addForm = this.$options.data().addForm
    },
    //根据ID获取logo图
    getqueryIdLogoImg(id) {
      this.compileBtn = false
      this.logoId = id
      queryIdLogoImg({ id: id }).then(({ data }) => {
        Object.keys(this.addForm).forEach(key => this.addForm[key] = data[key])
        this.addForm.batch = data.batch.split(',')
        this.addForm.child_admin = data.child_admin.split(',')
        this.logoImage = ""
        this.logShow = true
      }).catch(err => { })
    },
    //修改设备
    geteditLogoImg(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.addForm.id = this.logoId
          this.addForm.userId = localStorage.getItem("ID")
          this.addForm.last_ip = sessionStorage.getItem("Ip")
          editLogoImg(this.addForm).then(res => {
            this.$message.success(res.msg)
            this.getqueryLogoImg()
            this.logShow = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //上传压缩包
    beforeAvatarUpload(event) {
      this.videoUploadPercent = Math.floor(event.percent)
    },
    beforeZip(file) {
      if (file.name == 'bootanimation.zip') {
        return true
      } else {
        this.$message.error('ZIP包名称必须为：bootanimation.zip 请手动修改包名')
        return false
      }
    },
    //添加按钮
    addLogo() {
      this.logShow = true
      this.compileBtn = true
    },
    //增加卡机logo图
    getaddLogoImg(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.addForm.userId = localStorage.getItem("ID")
          this.addForm.last_ip = sessionStorage.getItem("Ip")
          addLogoImg(this.addForm).then(res => {
            this.$message.success(res.msg)
            this.getqueryLogoImg()
            this.logShow = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //获取批次
    getBatchTwos() {
      getBatchTwo({ userId: localStorage.getItem("ID") }).then(res => {
        this.batchData = res.data
      }).catch(err => {
        this.batchData = []
      })
    },
    //文件上传
    logoUpload(file, fileList) {
      this.addForm.file_size=file.size
      const bmf = new BMF()
      bmf.md5(file.raw, (err, md5) => {//获取文件MD5
        this.addForm.file_md5 = md5
      });
      ossFile(file.raw,file.name).then(ossUrl => {//文件上传
        this.videoUploadPercent = 0
        this.addForm.file_url=ossUrl
        this.$message.success("上传成功")
      }).catch(err => {
        this.$message.error("文件上传失败")
      })
    },
    getqueryLogoImg() {
      queryLogoImg(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
      }).catch(err => {
        this.total = 0
        this.browserTable = []
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryLogoImg();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryLogoImg();
    },
    Refresh() {
      this.listQuery = { userId: localStorage.getItem("ID"), startSize: 1, pageSize: 10, username: undefined }
      this.getqueryLogoImg()
    },
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.username = this.searchInput
          this.getqueryLogoImg();
          break;
      }
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.log {
  position: absolute;
  height: 100%;
  width: 100%;
}
.content_left {
  background-color: #394350;
  height: 100%;
  color: #ffffff;
  .log-picture {
    padding: 20px;
    h2 {
      font-weight: 500;
    }
  }
  .upLogo {
    margin-top: 20px;
    .logo_Title {
      margin-right: 5px;
    }
    .upload-demo {
      position: relative;
      right: 10px;
    }
    .logo_upload {
      width: 75%;
      position: relative;
    }
    .logoBtn {
      text-align: center;
    }
  }
  .facility {
    text-align: center;
  }
  .picture {
    text-align: center;
    margin-top: 40px;
  }
  .logo_text {
    margin-top: 40px;
    display: flex;
    justify-content: center;
    span {
      display: inline-block;
      width: 250px;
      font-size: 14px;
      line-height: 25px;
      p {
        margin: 0;
        font-size: 16px;
        padding-bottom: 10px;
      }
    }
  }
  .download-log {
    margin-top: 40px;
    display: flex;
    justify-content: center;
    .download-template {
      width: 250px;
      a {
        background-color: #252e3c;
        height: 40px;
        display: block;
        line-height: 40px;
        width: 110px;
        text-align: center;
        color: #70a1e2;
      }
    }
  }
}
.logo_confirm {
  text-align: center;
  margin-top: 50px;
}
.content_right {
  text-align: center;
  background-color: #1f2731;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .default-img {
    // width: 419px;
    // height: 700px;
    img {
      width: 100%;
      height: 100%;
    }
    .zipTxt {
      color: #ffffff;
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }
}
.closeBtn {
  position: absolute;
  top: 10px;
  right: 20px;
}
.uplogoRule {
  cursor: pointer;
}
</style>

<style scoped>
/deep/ .el-progress__text {
  color: #fff;
}
/deep/ .el-button.is-round {
  border-radius: 4px;
}
</style>
